#include "public_server.h"
#include "protocol.h"
#include "string.h"

// 查询软件版本信息
__WEAK void server_read_ver(protocol_frame_t frame)
{
    uint8_t buf[64] = {0};
    buf[0] = 0x01;
    buf[1] = (MOD_VERSION >> 16) & 0xff;
    buf[2] = (MOD_VERSION >> 8) & 0xff;
    buf[3] = (MOD_VERSION >> 0) & 0xff;
    strcat((char *)&buf[4], (const char *)BUILD_TIME);
    protocol_result(frame, buf, 4 + strlen(BUILD_TIME));
}
APP_SERVER(CMD_STA_GET_VERSION, server_read_ver);

// 读取板卡中的自定义参数
__WEAK void server_get_fal_param(protocol_frame_t frame)
{
    protocol_result(frame, NULL, 0);
}
APP_SERVER(CMD_STA_GET_FAL_PARAM, server_get_fal_param);

// 写入自定义参数到板卡中
__WEAK void server_set_fal_param(protocol_frame_t frame)
{
    protocol_result(frame, NULL, 0);
}
APP_SERVER(CMD_STA_SET_FAL_PARAM, server_set_fal_param);

// 查询字符串调试信息
__WEAK void server_get_debug_str(protocol_frame_t frame)
{
    protocol_result(frame, NULL, 0); // 返回空表示成功
}
APP_SERVER(CMD_STA_GET_DEBUG_STR, server_get_debug_str);

// 保存参数到flash
__WEAK void server_save_param_to_flash(protocol_frame_t frame)
{
    // 这里应调用实际的flash保存函数
    // save_param_to_flash(fal_param, FAL_PARAM_SIZE);
    protocol_result(frame, NULL, 0);
}
APP_SERVER(CMD_STA_SAVE_PARAM_TO_FLASH, server_save_param_to_flash);

// 从flash加载参数
__WEAK void server_load_param_from_flash(protocol_frame_t frame)
{
    // 这里应调用实际的flash加载函数
    // load_param_from_flash(fal_param, FAL_PARAM_SIZE);
    protocol_result(frame, NULL, 0);
}
APP_SERVER(CMD_STA_LOAD_PARAM_FROM_FLASH, server_load_param_from_flash);

// 下位机主动返回，通知进入APP代码段
__WEAK void server_app_ready(protocol_frame_t frame)
{
    char data[] = "APP ready";
    protocol_result(frame, (uint8_t *)data, sizeof(data));
}
APP_SERVER(CMD_STA_APP_READY, server_app_ready);

// 下位机板卡软复位
__WEAK void server_soft_reset(protocol_frame_t frame)
{
    protocol_result(frame, NULL, 0);
    // 实际复位操作应在协议返回后执行
    NVIC_SystemReset();
}
APP_SERVER(CMD_ACT_SOFT_RESET, server_soft_reset);

// 板卡握手
__WEAK void server_handshake(protocol_frame_t frame)
{
    protocol_result(frame, frame->data, frame->status_code.para_len);
}
APP_SERVER(CMD_ACT_HANDSHAKE, server_handshake);

// 设置板卡状态LED显示输出
__WEAK void server_set_led(protocol_frame_t frame)
{
    // TODO: 实现LED控制逻辑
    protocol_result(frame, NULL, 0);
}
APP_SERVER(CMD_ACT_SET_LED, server_set_led);

// 跳入BOOT代码段并进入IAP模式
__WEAK void server_jump_to_boot(protocol_frame_t frame)
{
    protocol_result(frame, NULL, 0);
    // TODO
    //  实际跳转操作应在协议返回后执行
    //  jump_to_boot();
}
APP_SERVER(CMD_ACT_JUMP_TO_BOOT, server_jump_to_boot);

// BOOT相关命令可在bootloader工程中实现